package web.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import web.bo.MyUploadRecordBo;
import web.common.CutPageBean;
import web.common.Result;
import web.entity.MyUploadSearchBo;
import web.entity.Security_UserDetail;
import web.entity.admin.user.MyuploadEntity;
import web.mapper.MyUploadMysqlMapper;
import web.service.MyUploadService;
import web.utils.FileuploadUtils;
import web.utils.RandomUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MyUploadServiceImpl
 */

@Service
public class MyUploadServiceImpl implements MyUploadService {

    @Autowired
    private MyUploadMysqlMapper myUploadMysqlMapper;


    @Value("${filePath.bdgrfilepath}")
    private String bdgrfilepath;


    @Override
    public CutPageBean<MyuploadEntity> getList(Integer page, Integer pageSize, String keyWord, String type) {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Security_UserDetail user = (Security_UserDetail) authentication.getPrincipal();
        String accountAdmin = user.getUserDo().getAccount();
        MyUploadSearchBo searchBo =new MyUploadSearchBo();
        searchBo.setPage(page);
        searchBo.setPageSize(pageSize);
        searchBo.setAccount(accountAdmin);
        searchBo.setStart(page,pageSize);
        searchBo.setName(keyWord);
        searchBo.setSearchType(type);
        List<MyuploadEntity> res = myUploadMysqlMapper.getList(searchBo);
        Integer count = myUploadMysqlMapper.count(searchBo);
        CutPageBean<MyuploadEntity> cutPage=new CutPageBean<>();
        cutPage.initCutPage(count, searchBo.getPageSize(), res);
        return cutPage;
    }

    /**
     * 上传 源文件
     * @param file 源文件
     * @return 返回源文件的信息保存到mysql表
     */
    @Override
    public Result uploadFile(MultipartFile file) {
        //生成的uuid，作为文件名
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        //返回上传文件信息map
        Map<String, String> resultMap = new HashMap<>(4);
        //生成的uuid，作为文件名
        resultMap.put("fileName", fileName);
        // 文件原始名称
        resultMap.put("sourceName", file.getOriginalFilename());
        try {
            String filePath = new File(bdgrfilepath).toString();
            // 文件保存的目录
            resultMap.put("filePath", bdgrfilepath);
            //执行保存(文件,目录,文件名)
            web.utils.FileUtil.saveFile(file, filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getLocalizedMessage());
        }
        return Result.succ(resultMap);
    }

    /**
     * 下载 源文件
     * @param id 源文件id
     */
    @Override
    public void downloadFile(Integer id, HttpServletResponse response) {

        MyuploadEntity myuploadEntity = myUploadMysqlMapper.selectById(id);

        //文件路径
        String filePath = myuploadEntity.getFilePath();
        //转换后的文件名
        String fileName = myuploadEntity.getFileName();
        //源文件名
        String sourceName = myuploadEntity.getSourceName();

        FileuploadUtils.downloadMyUpload(filePath+fileName, response,sourceName);
    }

    /**
     * 保存上传的文件记录信息
     * @param recordBo 上传的文件记录信息
     * @return Result
     */
    @Override
    public Result save(MyUploadRecordBo recordBo) {

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Security_UserDetail user = (Security_UserDetail) authentication.getPrincipal();
        String accountAdmin = user.getUserDo().getAccount();
        int depId = user.getUserDo().getDep_id();


        MyuploadEntity entity = new MyuploadEntity();
        entity.setName(recordBo.getName());
        entity.setKeyword(recordBo.getKeyword());
        entity.setNotes(recordBo.getNotes());
        entity.setAuthor(recordBo.getAuthor());
        entity.setType(recordBo.getType());
        entity.setSourceName(recordBo.getSourceName());
        entity.setFilePath(recordBo.getFilePath());
        entity.setFileName(recordBo.getFileName());
        entity.setCreateTime(RandomUtils.nowStr(""));
        entity.setCreateUser(accountAdmin);
        entity.setDepId(depId);

        int result =  myUploadMysqlMapper.insert(entity);

        if (result==1){
            return Result.succ("保存上传信息成功！");
        }

        return Result.fail("保存上传信息失败！");
    }

    /**
     * 修改上传的文件记录信息
     * @param recordBo 上传的文件记录信息
     * @return Result
     */
    @Override
    public Result edit(MyUploadRecordBo recordBo) {

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Security_UserDetail user = (Security_UserDetail) authentication.getPrincipal();
        String accountAdmin = user.getUserDo().getAccount();

        MyuploadEntity entity = myUploadMysqlMapper.selectById(recordBo.getId());
        if (entity==null){
            return Result.fail("修改上传信息失败！");
        }

        entity.setName(recordBo.getName());
        entity.setKeyword(recordBo.getKeyword());
        entity.setNotes(recordBo.getNotes());
        entity.setAuthor(recordBo.getAuthor());
        entity.setType(recordBo.getType());
        entity.setSourceName(recordBo.getSourceName());
        entity.setFilePath(recordBo.getFilePath());
        entity.setFileName(recordBo.getFileName());
        entity.setEditTime(RandomUtils.nowStr(""));
        entity.setEditUser(accountAdmin);

        int result =  myUploadMysqlMapper.updateById(entity);

        if (result==1)
            return Result.succ("修改上传信息成功！");

        return Result.fail("修改上传信息失败！");
    }

    /**
     * 根据id，删除个人资料
     *
     * @param id 个人资料id
     * @return Result
     */
    @Override
    public Result delete(Integer id) {

        MyuploadEntity myuploadEntity = myUploadMysqlMapper.selectById(id);

        //删除文件
        web.utils.FileUtil.deleteFile(myuploadEntity.getFilePath()+myuploadEntity.getFileName());

        //删除MySQL表记录
        int result = myUploadMysqlMapper.deleteById(id);

        if (result==1)
            return Result.succ("删除文件成功！");

        return Result.fail("删除文件失败！");

    }

    /**
     * 删除上传的文件
     * @param pathFile 删除的文件路径
     * @return Result
     */
    @Override
    public Result deleteFile(String pathFile) {
        //删除文件
        web.utils.FileUtil.deleteFile(pathFile);
        return Result.succ("删除文件成功！");
    }

    /**
     * 根据id，获取信息
     * @param id 记录id
     * @return Result
     */
    @Override
    public Result detail(Integer id) {

        MyuploadEntity myuploadEntity = myUploadMysqlMapper.selectById(id);

        if (myuploadEntity!=null)
            return Result.succ(myuploadEntity);

        return Result.fail("获取详情失败！");
    }


    /***
     *  判断 源文件是否存在
     * @param id 记录id
     * @return Result
     */
    @Override
    public Result existFile(Integer id) {

        MyuploadEntity myuploadEntity = myUploadMysqlMapper.selectById(id);

        //文件路径
        String filePath = myuploadEntity.getFilePath();
        //转换后的文件名
        String fileName = myuploadEntity.getFileName();

        boolean flag = FileuploadUtils.existFile(filePath+fileName);

        if (flag){
            return Result.succ("存在");
        }

        return Result.fail("不存在");
    }
}
